/**
 * @fileOverview law.js
 * This is webServer's Fetch law data module that handles URL /law/*
 */

// Express router
const router = require("express").Router();
const { createNewTree, preOrderTraversal } = require("./utilities/lawUtil");

// import schema
const { Law, LawItem } = require("../schema/lawSchema");

// 获取一部处理后的法律数据
router.post("/law-handle", async (request, response) => {
  try {
    const id = request.body.id;
    const lawRoot = await Law.findById(id).lean();
    const root = await LawItem.findById(lawRoot.children);
    const lawTree = await createNewTree(root); //提取对应的节点
    response.status(200).send(lawTree);
  } catch (err) {
    console.error(err);
    response.status(500).send("获取数据失败");
  }
});

// 获取一部未处理的法律数据
router.post("/law-unhandle", async (request, response) => {
  try {
    const id = request.body.id;
    const unhandleLawData = [];
    const lawRoot = await Law.findById(id).lean();
    await preOrderTraversal(lawRoot.children, unhandleLawData);
    response.status(200).send(unhandleLawData);
  } catch (err) {
    console.error(err);
    response.status(500).send("获取数据失败");
  }
});

// 获取所有的法律的根节点
router.post("/law-root", async (request, response) => {
  try {
    const lawData = await Law.find({}).lean();
    response.status(200).send(lawData);
  } catch (err) {
    console.error(err);
    response.status(500).send("获取数据失败");
  }
});

module.exports = router;
